﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint;
using System.IO;

namespace SPEntityUtility
{
    public partial class SPColumnConstGen : Form
    {
        //validations                        
        public SPColumnConstGen()
        {
            InitializeComponent();
        }

        private void SPEntity_Load(object sender, EventArgs e)
        {

        }

        #region Events


        private void btnCreateEntities_Click(object sender, EventArgs e)
        {
            CreateListEntities();
        }

        private void btnShowList_Click(object sender, EventArgs e)
        {
            PopulateLists();

        }


        private void dgvList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex != -1)
            {
                dgvList.Rows[e.RowIndex].Selected = true;
                DataGridViewCheckBoxCell ch1 = new DataGridViewCheckBoxCell();

                ch1 = (DataGridViewCheckBoxCell)dgvList.Rows[dgvList.CurrentRow.Index].Cells[0];

                if (ch1.Value == null)

                    ch1.Value = false;

                switch (ch1.Value.ToString())
                {

                    case "True":

                        ch1.Value = false;

                        break;

                    case "False":

                        ch1.Value = true;

                        break;

                }
            }

        }

        #endregion

        #region Methods

        protected void PopulateLists()
        {
            string siteUrl = txtSiteUrl.Text;
            try
            {

                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    using (SPSite objsite = new SPSite(siteUrl))
                    {
                        using (SPWeb objWeb = objsite.OpenWeb())
                        {

                            SPListCollection lstColl = objWeb.Lists;
                            dgvList.DataSource = GetListsDatatable(lstColl);
                            dgvList.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
                            dgvList.Visible = true;
                            btnCreateEntities.Visible = true;
                            chkDefaultView.Visible = true;

                        }
                    }
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error Occured While retrieving the Site" + Environment.NewLine + "Please check the Site Url"
                                + Environment.NewLine + "Detailed Error Message: " + ex.Message);

            }

        }

        protected DataTable GetListsDatatable(SPListCollection lstColl)
        {
            DataTable dtLists = new DataTable();
            dtLists.Columns.Add("ListName");
            dtLists.Columns.Add("Author");
            dtLists.Columns.Add("DefaultView");

            foreach (SPList lst in lstColl)
            {
                DataRow drNew = dtLists.NewRow();
                drNew["ListName"] = lst.Title;
               // drNew["Author"] = lst.Author;
                drNew["DefaultView"] = lst.DefaultView;
                dtLists.Rows.Add(drNew);
            }


            return dtLists;
        }

        protected void CreateListEntities()
        {
            StringBuilder strMainFile = new StringBuilder();
            StringBuilder strMainListNames = new StringBuilder();
            strMainFile.AppendLine("using System;");
            strMainFile.AppendLine("using System.Collections.Generic;");
            strMainFile.AppendLine("using System.Linq;");
            strMainFile.AppendLine("using System.Text;");
            strMainFile.AppendLine("namespace SiteEntities");
            strMainFile.AppendLine("{");

            foreach (DataGridViewRow dgvr in dgvList.Rows)
            {
                DataGridViewCheckBoxCell chkSelect = new DataGridViewCheckBoxCell();
                chkSelect = (DataGridViewCheckBoxCell)dgvr.Cells["SelectList"];


                if (dgvr.Cells["SelectList"].FormattedValue.ToString().ToLower() == "true")//(chkSelect.Selected  )
                {
                    string listName = Convert.ToString(dgvr.Cells["ListName"].Value);
                    //get the list name and create entites in a string builder
                    strMainListNames.AppendLine(listName);
                    //Entity Classes
                    strMainFile.AppendLine(GetListEntities(listName).ToString());
                }

            }

            strMainFile.AppendLine("}");
            CreateFile(strMainFile.ToString());
            MessageBox.Show("Entities created for" + Environment.NewLine + strMainListNames.ToString());

        }

        protected StringBuilder GetListEntities(string listName)
        {
            string siteUrl = txtSiteUrl.Text;
            StringBuilder strEntities = new StringBuilder();
            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                using (SPSite objsite = new SPSite(siteUrl))
                {
                    using (SPWeb objWeb = objsite.OpenWeb())
                    {
                        SPList lst = objWeb.Lists.TryGetList(listName);

                        strEntities.AppendLine("public class " + listName.Replace(' ', '_') + "Entities");
                        strEntities.AppendLine("{");
                        foreach (SPField fld in lst.Fields)
                        {
                            if (UseDefaultView(lst, fld))
                            {
                                strEntities.Append("public const string");
                                string internalName = fld.InternalName;
                                string displayName = fld.Title.Replace(' ', '_');
                                if (internalName.ToLower() == "linktitle")
                                {
                                    internalName = "Title";
                                }
                                strEntities.AppendLine(" " + displayName + " =  \"" + internalName + "\";");
                            }
                        }
                        strEntities.AppendLine("}");
                    }
                }
            });

            return strEntities;


        }

        protected void CreateFile(string content)
        {
            WriteToFile(content, "mySite");

        }

        public void WriteToFile(string content, string siteName)
        {
            try
            {
                string fileName = GetUniqueFileName();// Environment.CurrentDirectory + "\\" + siteName + "_Entities.txt";
                if (!File.Exists(fileName))
                {

                    StreamWriter sw = File.CreateText(fileName);
                    sw.WriteLine(content);
                    sw.Close();
                }

            }
            catch (Exception ex)
            {

            }
        }

        protected string GetUniqueFileName()
        {
            if (!Directory.Exists(Environment.CurrentDirectory + "\\Entities"))
            {
                Directory.CreateDirectory(Environment.CurrentDirectory + "\\Entities");
            }
            int i = 1;
            string unqFileName = Environment.CurrentDirectory + "\\Entities\\" + "SPEntities_0" + ".txt";
            while (File.Exists(unqFileName))
            {
                unqFileName = Environment.CurrentDirectory + "\\Entities\\" + "SPEntities_" + i + ".txt";
                i++;
            }

            return unqFileName;

        }

        protected bool UseDefaultView(SPList lst, SPField fld)
        {
            bool existInDV = true;
            if (chkDefaultView.Checked)
            {
                existInDV = lst.DefaultView.ViewFields.Exists(fld.InternalName);
            }

            return existInDV;
        }

        #endregion





    }
}
